package com.ctg.itrdc.sysmgr.portal.utils;

import java.util.List;

import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;

import com.ctg.itrdc.pasp.security.SecUser;
import com.ctg.itrdc.pasp.security.utils.WebUtils;
import com.ctg.itrdc.sysmgr.portal.api.dto.BaseDTO;
import com.ctg.itrdc.sysmgr.portal.exception.SysmgrContrlException;
import com.google.common.collect.Lists;

public class DTOHelper {

	public static <T extends BaseDTO> void updateDTO(T dto) {
		SecUser ctgUser = WebUtils.getCtgUser();
		if(ctgUser!=null){
			Long createStaff = dto.getCreateStaff();
			if(createStaff==null){
				dto.setCreateStaff(ctgUser.getStaffId());
			}
			dto.setUpdateStaff(ctgUser.getStaffId()); // 每次都会更新
		}else{
			dto.setCreateStaff(-1l);
			dto.setUpdateStaff(-1l);
		}
	}
	
	public static void valid(BindingResult result){
		if(result.hasErrors()){
			List<String> errors = Lists.newArrayList();
			List<ObjectError> allErrors = result.getAllErrors();
			for (ObjectError tmpError : allErrors) {
				FieldError error = (FieldError)tmpError;
				String message = error.getField()+error.getDefaultMessage();
				errors.add(message);
			}
			throw new SysmgrContrlException(errors.toString());
		}
	}
}
